package com.tgpms.web.tongfei.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.tgpms.common.MultipartFileToFile;
import com.tgpms.common.Result;
import com.tgpms.web.tongfei.TongfeiController;
import com.tgpms.web.tongfei.entity.InLineParts;
import com.tgpms.web.tongfei.entity.Newpspipefile;
import com.tgpms.web.tongfei.pojo.Newpspipe;
import com.tgpms.web.tongfei.pojo.R;
import com.tgpms.web.tongfei.service.IInLinePartsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * <p>
 * 控制层
 * </p>
 *
 * @author jl
 * @since 2020-11-25
 */
@Api(value = "InLinePartsController", tags = "新建管网信息管道相关接口")
@RestController
@RequestMapping("/tongfei")
public class InLinePartsController {
    @Value("${tongfei.path}")
    private String host;
    private String addNewpspipe = "/tofly-sxgk/newpspipe"; // 新建管线
    @Resource
    private RedisTemplate<String, Object> redis;
    @Autowired
    private IInLinePartsService inLinePartsService;

    /**
     * 新增新建管网信息管道
     */
    @ApiOperation(value = "新增新建管网信息管道", notes = "新增新建管网信息管道", httpMethod = "POST")
    @PostMapping(value = "/tofly-sxgk/newpspipe", headers = "content-type=multipart/form-data")
    public Result addNewpspipe(@RequestParam(value = "newpspipe") String jsonString, HttpServletRequest request) {
        InLineParts inLineParts = JSON.parseObject(jsonString, InLineParts.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(inLineParts.getNewpspipefileList())) {
                List<Newpspipefile> newpspipefileList = inLineParts.getNewpspipefileList();
                for (int i = 0; i < newpspipefileList.size(); i++) {
                    Newpspipefile newpspipefile = newpspipefileList.get(i);
                    paramMap.put("newpspipefileList[" + i + "].fileName", newpspipefile.getFileName());
                    paramMap.put("newpspipefileList[" + i + "].distance", newpspipefile.getDistance());
                    paramMap.put("newpspipefileList[" + i + "].latitude", newpspipefile.getLatitude());
                    paramMap.put("newpspipefileList[" + i + "].longitude", newpspipefile.getLongitude());
                    paramMap.put("newpspipefileList[" + i + "].sxCoor", newpspipefile.getSxCoor());
                    paramMap.put("newpspipefileList[" + i + "].syCoor", newpspipefile.getSyCoor());
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(newpspipefile.getFileName(), image);
                    images.add(image);
                }
            }

            // 工序集合
//            if (CollectionUtil.isNotEmpty(inLineParts.getNewpspipepdList())) {
//                List<Newpspipepd> newpspipepdList = inLineParts.getNewpspipepdList();
//                for (int i = 0; i < newpspipepdList.size(); i++) {
//                    Newpspipepd newpspipepd = newpspipepdList.get(i); // 工序
//                    // 图片集合
//                    if (CollectionUtil.isNotEmpty(newpspipepd.getNewpspipefileList())) {
//                        List<Newpspipefile> newpspipefileList = newpspipepd.getNewpspipefileList();
//                        for (int j = 0; j < newpspipefileList.size(); j++) {
//                            Newpspipefile newpspipefile = newpspipefileList.get(j); //图片
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].fileName", newpspipefile.getFileName());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].distance", newpspipefile.getDistance());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].latitude", newpspipefile.getLatitude());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].longitude", newpspipefile.getLongitude());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].sxCoor", newpspipefile.getSxCoor());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].syCoor", newpspipefile.getSyCoor());
//                            File image = MultipartFileToFile.multipartFileToFile(files.get(i));
//                            paramMap.put(newpspipefile.getFileName(), image);
//                            images.add(image);
//                        }
//                    }
//
//                    paramMap.put("newpspipepdList[" + i + "].notes", newpspipepd.getNotes());
//                    paramMap.put("newpspipepdList[" + i + "].pdCode", newpspipepd.getPdCode());
//                }
//            }

            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(inLineParts, false, true));
            paramMap.remove("newpspipefileList");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.post(host + addNewpspipe)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地新增
                String json = JSON.toJSONString(r.getResult());
                Newpspipe data = JSON.parseObject(json, Newpspipe.class);
                inLineParts.setRowstamp(String.valueOf(data.getId()));
                inLineParts.setInsertUser(this.getUsername(token));
                return inLinePartsService.addInLineParts(inLineParts);
            } else {
                MultipartFileToFile.delteTempFile(images);
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 修改新增新建管网信息管道
     */
    @ApiOperation(value = "修改新增新建管网信息管道", notes = "修改新增新建管网信息管道", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/updateNewpspipe")
    public Result updateNewpspipe(@RequestParam(value = "newpspipe") String jsonString, HttpServletRequest request) {
        Newpspipe newpspipe = JSON.parseObject(jsonString, Newpspipe.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 工序集合
//            if (CollectionUtil.isNotEmpty(newpspipe.getNewpspipepdList())) {
//                List<Newpspipepd> newpspipepdList = newpspipe.getNewpspipepdList();
//                for (int i = 0; i < newpspipepdList.size(); i++) {
//                    Newpspipepd newpspipepd = newpspipepdList.get(i); // 工序
//                    // 图片集合
//                    if (CollectionUtil.isNotEmpty(newpspipepd.getNewpspipefileList())) {
//                        List<Newpspipefile> newpspipefileList = newpspipepdList.get(i).getNewpspipefileList();
//                        for (int j = 0; j < newpspipefileList.size(); j++) {
//                            Newpspipefile newpspipefile = newpspipefileList.get(j); //图片
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].fileName", newpspipefile.getFileName());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].distance", newpspipefile.getDistance());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].latitude", newpspipefile.getLatitude());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].longitude", newpspipefile.getLongitude());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].sxCoor", newpspipefile.getSxCoor());
//                            paramMap.put("newpspipepdList[" + i + "].newpspipefileList[" + j + "].syCoor", newpspipefile.getSyCoor());
//                            File image = MultipartFileToFile.multipartFileToFile(files.get(i));
//                            paramMap.put(newpspipefile.getFileName(), image);
//                            images.add(image);
//                        }
//                    }
//
//                    paramMap.put("newpspipepdList[" + i + "].notes", newpspipepd.getNotes());
//                    paramMap.put("newpspipepdList[" + i + "].pdCode", newpspipepd.getPdCode());
//                }
//            }
            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(newpspipe, false, true));
            paramMap.remove("newpspipepdList");
            paramMap.remove("createTime");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.put(host + addNewpspipe)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地修改
                String json = JSON.toJSONString(r.getResult());
                Newpspipe data = JSON.parseObject(json, Newpspipe.class);
                InLineParts inLineParts = inLinePartsService.getInLinePartsByRowstamp(String.valueOf(data.getId()));
                BeanUtil.copyProperties(data, inLineParts, "id");
                inLineParts.setModifyUser(this.getUsername(token));
                inLineParts.setModifyDate(new Date());
                return inLinePartsService.updateInLineParts(inLineParts);
            } else {
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 分页查询新增新建管网信息管道
     */
    @ApiOperation(value = "分页查询新增新建管网信息管道", notes = "分页查询新增新建管网信息管道", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/newpspipe/page")
    public Result page(Newpspipe newpspipe, HttpServletRequest request) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(newpspipe, false, true);
        paramMap.put("orders[0].column", "create_time");
        paramMap.put("orders[0].asc", false);
        return TongfeiController.normalGet("/tofly-sxgk/newpspipe/page", paramMap, request);
    }

    /**
     * 查询固件最新的扫描数据
     */
    @ApiOperation(value = "查询固件最新的扫描数据", notes = "查询固件最新的扫描数据", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/newpspipe/getNewScanInfo")
    public Result getNewScanInfo(@RequestParam("pbs") String pbs, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("pbs", pbs);
        return TongfeiController.normalGet("/tofly-sxgk/newpspipe/getNewScanInfo", paramMap, request);
    }

    /**
     * 查询同类型人员固件最新的扫描数据
     */
    @ApiOperation(value = "查询同类型人员固件最新的扫描数据", notes = "查询同类型人员固件最新的扫描数据", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/newpspipe/getNewScanInfoByType")
    public Result getNewScanInfoByType(@RequestParam("pbs") String pbs, HttpServletRequest request) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("pbs", pbs);
        return TongfeiController.normalGet("/tofly-sxgk/newpspipe/getNewScanInfoByType", paramMap, request);
    }

    private String getUsername(String token) {
        return (String) redis.opsForValue().get(token);
    }
}
